package com.baichuan.zntx.service.impl;

import com.baichuan.common.core.utils.MapstructUtils;
import com.baichuan.common.core.utils.StringUtils;
import com.baichuan.common.mybatis.core.page.TableDataInfo;
import com.baichuan.common.mybatis.core.page.PageQuery;
import com.baichuan.zntx.common.GPSUtils;
import com.baichuan.zntx.domain.Command;
import com.baichuan.zntx.domain.Location;
import com.baichuan.zntx.domain.Task;
import com.baichuan.zntx.domain.vo.CalibrateVo;
import com.baichuan.zntx.domain.vo.RegionVo;
import com.baichuan.zntx.mapper.CalibrateMapper;
import com.baichuan.zntx.mapper.RegionMapper;
import com.baichuan.zntx.mapper.TaskMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.baichuan.zntx.domain.bo.DeviceBo;
import com.baichuan.zntx.domain.vo.DeviceVo;
import com.baichuan.zntx.domain.Device;
import com.baichuan.zntx.mapper.DeviceMapper;
import com.baichuan.zntx.service.IDeviceService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 智能铁鞋Service业务层处理
 *
 * @author Baichuan
 * @date 2024-05-11
 */
@RequiredArgsConstructor
@Service
public class DeviceServiceImpl implements IDeviceService {

    private final DeviceMapper baseMapper;
    private final CalibrateMapper calibrateMapper;
    private final TaskMapper taskMapper;
    private final RegionMapper regionMapper;
    /**
     * 查询智能铁鞋
     */
    @Override
    public DeviceVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询智能铁鞋列表
     */
    @Override
    public TableDataInfo<DeviceVo> queryPageList(DeviceBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Device> lqw = buildQueryWrapper(bo);
        Page<DeviceVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<CalibrateVo> calibrateVos = calibrateMapper.selectVoList(null);
        result.getRecords().forEach(item -> {
            //是否工作中且存在工位
            if(item.getStatus() == 0 && StringUtils.isNotEmpty(item.getRegion())){
                RegionVo regionVo = regionMapper.selectVoById(item.getRegion());
                if(regionVo!=null && regionVo.getIsAvailable() == 1){
                    //把设备放置到指定工位
                    Location loc = new Location(regionVo.getLatitude(), regionVo.getLongtitude());
                    item.setPixelLocation(loc);
                }
            }else{
                Location loc = GPSUtils.GpsToPixel(calibrateVos, new Location(item.getLatitude(), item.getLongtitude()));
                item.setPixelLocation(loc);
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询智能铁鞋列表
     */
    @Override
    public List<DeviceVo> queryList(DeviceBo bo) {
        LambdaQueryWrapper<Device> lqw = buildQueryWrapper(bo);

        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Device> buildQueryWrapper(DeviceBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Device> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getDeviceId()), Device::getDeviceId, bo.getDeviceId());
        lqw.eq(bo.getTrack() != null, Device::getTrack, bo.getTrack());
        lqw.eq(bo.getWheel() != null, Device::getWheel, bo.getWheel());
        lqw.eq(bo.getGpsStatus() != null, Device::getGpsStatus, bo.getGpsStatus());
        return lqw;
    }

    /**
     * 新增智能铁鞋
     */
    @Override
    public Boolean insertByBo(DeviceBo bo) {
        Device add = MapstructUtils.convert(bo, Device.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改智能铁鞋
     */
    @Override
    public Boolean updateByBo(DeviceBo bo) {
        Device update = MapstructUtils.convert(bo, Device.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    @Override
    public Boolean update(Device bo) {
        int x = baseMapper.updateById(bo);
        return x> 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Device entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除智能铁鞋
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Device queryBuDeviceId(String id) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Device>().eq(Device::getDeviceId, id));
    }

    @Override
    public List<DeviceVo> listByTask(Integer type) {
        if(type == 0){
            //安装任务
            List<DeviceVo> data = baseMapper.selectVoList(new LambdaQueryWrapper<Device>()
                .eq(Device::getStatus, 8));
            //返回空闲状态且不存在未完成任务的设备
            return data.stream().filter(item -> {
                long count = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
                    .eq(Task::getDeviceId, item.getDeviceId()).in(Task::getStatus,0, 1));
                return count==0;
            }).toList();
        }else if(type == 1){
            //拆除任务
            List<DeviceVo> data = baseMapper.selectVoList(new LambdaQueryWrapper<Device>()
                .eq(Device::getStatus, 0));
            //返回工作中且不包含未完成拆除任务的设备
            return data.stream().filter(item -> {
                long count = taskMapper.selectCount(new LambdaQueryWrapper<Task>()
                    .eq(Task::getDeviceId, item.getDeviceId()).in(Task::getStatus,0, 1));
                return count==0;
            }).toList();
        }
        return null;
    }
}
